package org.example.domain.model.service;

import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.example.domain.model.entity.url.UrlShortener;
import org.example.domain.model.entity.url.req.RecycleBinPageReq;
import org.example.domain.model.entity.url.req.RecycleBinReq;
import org.example.domain.repository.RecycleBinServiceRepository;
import org.example.infrastructure.repository.orm.redis.config.constant.RedisCacheConstant;
import org.example.infrastructure.repository.remote.RemoteUrlShortenerGroupRepository;
import org.example.web.exception.ServerException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class RecycleBinDomainService {
    private final RecycleBinServiceRepository recycleBinServiceRepository;
    private final StringRedisTemplate stringRedisTemplate;
    private final RemoteUrlShortenerGroupRepository remoteUrlShortenerGroupRepository;

    public void saveRecycleBin(RecycleBinReq recycleBinReq) {
        recycleBinServiceRepository.saveRecycleBin(recycleBinReq.getGid(), recycleBinReq.getFullShortUrl());
        stringRedisTemplate.delete(RedisCacheConstant.SKIP_SHORT_LINK_KEY + recycleBinReq.getFullShortUrl());
    }

    public PageInfo<UrlShortener> recycleBinPage(RecycleBinPageReq recycleBinPageReq, String userName) {
        List<String> gidList = remoteUrlShortenerGroupRepository.selectGitListByUserName(userName);
        if (CollectionUtils.isEmpty(gidList)) {
            throw new ServerException("No git list found!");
        }
        PageInfo<UrlShortener> urlShortenerIPage = recycleBinServiceRepository.recycleBinPage(recycleBinPageReq, gidList);
        return urlShortenerIPage.convert(item->{
            item.setDomain("http://" + item.getDomain());
            return item;
        });
    }

    public void recoverRecycleBin(RecycleBinReq recycleBinReq) {
        recycleBinServiceRepository.recoverRecycleBin(recycleBinReq.getGid(), recycleBinReq.getFullShortUrl());
        stringRedisTemplate.delete(RedisCacheConstant.SKIP_SHORT_LINK_NULL_KEY + recycleBinReq.getFullShortUrl());
    }

    public void removeRecycleBin(RecycleBinReq recycleBinReq) {
        recycleBinServiceRepository.removeRecycleBin(recycleBinReq.getGid(), recycleBinReq.getFullShortUrl());
    }
}
